// pages/my-shop/my-shop.js
const app = getApp()
let LiuLanNum = 0
let id = ''
let shopId = ''
let count = 20
var name = null

Page({
  /**
   * 页面的初始数据
   */
  data: {
    name: '',
    zhuying: '',
    tese: '',
    tel: '',
    map: '',
    images: [],
    liulan: 0,
    weixin: '',
    id: '',
    TabCur: 0,
    scrollLeft: 0,
    Tab: ['商家动态', '商家福利'],
    currentIndex: 0,
    youhuiList: [],
    bossOpenId: '',
    userOpenId: '',
    hasShop:2,
   
    isDel: false,
    shopDetailAd: null
  },
  onLoad: function (e) {
    // 获取用户openid
    // 入驻店铺的是  undefined
    // 从店铺列表进入的  b00064a760faeef729bc187257dad56f
    // 获取店铺优惠列表

    this.setData({
      name: e.name,
      shopDetailAd: app.globalData.ads.shopDetailAd
    })
    this._loadYouhuiList()
    // 福利详情页进入的
    if (e.openid2) {

      this.selectMyShop2(e.openid2)
      return
    }
    // 老板
    if (e.openid) {
      // console.log(e.openid, '+++++++++++++++++++')
      this.selectMyShop()
      return
    }
    if (e.id && e.id == 'ruzhu_ok') {
      console.log('是入驻店铺进来的')
      this.selectMyShop()
      // 用户
    } else if (e.id) {
      console.log('是从店铺列表进来的')
      shopId = e.id
      wx.setNavigationBarTitle({
        title: '店铺详情',
      })
      this.selectMyShopById()
    } else {
      console.log('是点击朋友圈分享进来的')
      wx.setNavigationBarTitle({
        title: '店铺详情',
      })
      for (var key in e) {
        if (e.hasOwnProperty(key))
          console.log(JSON.parse(key).data); //键名
        shopId = JSON.parse(key).data
        this.selectMyShopById()
      }
    }
  },
  // 删除店铺和福利数据
  delMyShop(e) {
    console.log(e.currentTarget.dataset.openid, '删除店铺和福利数据')
    let openid = e.currentTarget.dataset.openid
    wx.showModal({
      title: '提示',
      content: '你确定要删除店铺数据吗？',
      success: res => {
        if (res.confirm) {
          wx.showLoading({
            title: '删除中...',
          })
          wx.cloud.callFunction({
              name: 'delMyShop',
              data: {
                openid
              }
            })
            .then(res => {
              console.log(res, '删除ok')
              wx.hideLoading({
                success: () => {
                  wx.switchTab({
                    url: '/pages/news/news',
                  })
                },
              })
            })
            .catch(res => {
              console.log(res, '删除fail')
            })

        }
      },

    })
  },
  // 加载福利列表
  _loadYouhuiList(start = 0) {
    wx.showLoading({
      title: '拼命加载中',
    })
    wx.cloud.callFunction({
        name: 'youhui',
        data: {
          start,
          count,
          tag: 'name',
          name: this.data.name
        }
      })
      .then(res => {
        wx.hideLoading()
        if (res.result.data.length == 0) {
          // 如果优惠列表查询为0，说明没有福利，给数据库isfuli 字段设置为false
          // 给店铺插入一条isfuli 为true
          console.log('===================', this.data.id)
          wx.cloud.callFunction({
            name: 'myShop',
            data: {
              tag: 'update_isfuli',
              id: this.data.id,
              isfuli: false
            }
          }).then(res => {
            console.log(res, "插入isfuli ok")
          }).catch(res => {
            console.log(res, "插入isfuli fail")
          })
        }
        // bossOpenId
        this.setData({
          youhuiList: this.data.youhuiList.concat(res.result.data),
          bossOpenId: res.result.data[0]._openid,
          userOpenId: res.result.openid
        })
        if (this.data.bossOpenId == this.data.userOpenId) {
          console.log('要显示删除按钮')

          this.setData({
            isDel: true
          })
        } else {
          console.log('不显示删除按钮')
          this.setData({
            isDel: false
          })
        }
      })
      // .catch(res => {
      //   console.log(res, '优惠列表查询失败')
      // })
    wx.hideLoading()
    wx.showToast({
      title: '加载成功',
    })

  },
  // 商家删除福利
  delMyNews(e) {
    console.log(e.currentTarget.dataset.newsid, '点击了删除优惠')
    // 去数据库删除该id下的福利
    let id = e.currentTarget.dataset.newsid
    wx.cloud.database().collection('youhui')
      .doc(id)
      .remove()
      .then(res => {
        console.log(res, '删除福利--------------------------')
        this.setData({
          youhuiList: []
        })
        this._loadYouhuiList()
        wx.showToast({
          icon: 'none',
          title: '删除成功',
        })
      })
      .catch(res => {
        console.log(res, '删除数据失败')
      })
  },
  // 放大显示图片2
  onPreviewImage(e) {
    console.log('点击了图片', e)
    wx.previewImage({
      urls: this.data.images,
      current: e.target.dataset.imagesrc
    })
  },
  tabSelect(e) {
    console.log(e.currentTarget.dataset.id)
    let current = e.currentTarget.dataset.id
    if (current == 0) {
      this.setData({
        currentIndex: 0
      })
    } else if (current == 1) {
      this.setData({
        currentIndex: 1
      })
    }
    this.setData({
      TabCur: e.currentTarget.dataset.id,
      scrollLeft: (e.currentTarget.dataset.id - 1) * 60
    })
  },
  // 拨号
  callphone() {
    wx.makePhoneCall({
      phoneNumber: this.data.tel
    })
  },
  // 复制微信号
  copyWx(e) {
    wx.setClipboardData({
      data: e.currentTarget.dataset.weixin
    })
  },
  // 打开地图定位
  openMap() {
    wx.openLocation({
      latitude: this.data.map.latitude,
      longitude: this.data.map.longitude,
      scale: 18
    })
  },
  // 入驻完成跳转到我的店铺页面，从数据库获取数据并渲染
  selectMyShop() {
    wx.cloud.callFunction({
        name: 'getShop',
        data: {
          tag: 'boss'
        }
      })
      .then(res => {
        console.log(res, 'boss数据获取成功')
        let data = res.result[0]
        this.setData({
          hasShop:1,
          name: data.getName,
          zhuying: data.getZhuYing,
          tese: data.getTeSe,
          tel: data.getTel,
          map: data.address,
          images: data.img,
          liulan: data.liulan,
          weixin: data.getWx,
          id: data._id,
          openId: data._openid
        })
        this.addLiuLanNum()
        this._loadYouhuiList()
      })
  },
  selectMyShop2(openid2) {
    wx.cloud.callFunction({
        name: 'getShop',
        data: {
          tag: 'OPENID',
          openid: openid2
        }
      })
      .then(res => {
        console.log(res, 'boss数据获取成功')
        let data = res.result[0]
        wx.setNavigationBarTitle({
          title: data.getName,
        })
        this.setData({
          hasShop:true,
          name: data.getName,
          zhuying: data.getZhuYing,
          tese: data.getTeSe,
          tel: data.getTel,
          map: data.address,
          images: data.img,
          liulan: data.liulan,
          weixin: data.getWx,
          id: data._id,
          openId: data._openid
        })
        this.addLiuLanNum()
        this._loadYouhuiList()
      })
  },
  // 根据id获取店铺数据
  selectMyShopById() {
    wx.cloud.callFunction({
        name: 'getShop',
        data: {
          id: shopId,
          tag: 'user',
        }
      })
      .then(res => {
        console.log(res.result, '根据id获取店铺数据ok')
        let data = res.result
        this.setData({
          hasShop:1,
          name: data.getName,
          zhuying: data.getZhuYing,
          tese: data.getTeSe,
          tel: data.getTel,
          map: data.address,
          images: data.img,
          liulan: data.liulan,
          weixin: data.getWx,
          id: data._id,
          openId: data._openid
        })
        this.addLiuLanNum()
      })
      .catch(res => {
        console.log(res, '根据id获取店铺数据fail')
      })
  },
  addLiuLanNum() {
    // LiuLanNum += 1
    wx.cloud.callFunction({
      name: 'myShop',
      data: {
        id: this.data.id,
        liulan: this.data.liulan + 1
      }
    }).then(res => {
      // console.log(res, '页面浏览量增加1次ok')
    }).catch(res => {
      console.log(res, '页面浏览量增加1次fail')
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (options) {
    console.log(options, '点击了分享')
    let id = options.target.dataset.newsid
    let title = options.target.dataset.news.content
    // let newsObj = e.target.dataset.news
    return {
      title: title,
      path: `/pages/my-shop/my-shop?id=${id}`,
      imageUrl: ''
    }
  },
  onShareTimeline: function (res) {
    var query = {
      data: this.data.id
    }
    query = JSON.stringify(query)
    return {
      title: this.data.name + '发福利啦,' + this.data.tese,
      query: query,
      imageUrl: '/images/fuli.png',
    }
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      youhuiList: []
    })
    this._loadYouhuiList(0)
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.youhuiList.length < count) {
      wx.showToast({
        icon: 'none',
        title: '没有更多数据了',
      })
      return;
    }
    this._loadYouhuiList(this.data.youhuiList.length)
  },
})